import express, { Request, Response, Router } from 'express';
import bcrypt from 'bcryptjs';
import { PrismaClient } from '@prisma/client';
import response from '../utils/response';
import { generateToken, authenticateToken } from '../middleware/auth';

// 扩展Request接口以包含user属性
interface AuthenticatedRequest extends Request {
  user?: {
    id: number;
    username: string;
    role: string;
  };
}

const router: Router = express.Router();
const prisma = new PrismaClient();

// 管理员登录
router.post('/login', async (req: Request, res: Response) => {
  try {
    const { username, password } = req.body;

    if (!username || !password) {
      return response.error(res, '请输入用户名和密码');
    }

    // 查找管理员
    const admin = await prisma.admin.findUnique({
      where: { username }
    });

    if (!admin) {
      return response.error(res, '用户名或密码错误');
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, admin.password);
    if (!isValidPassword) {
      return response.error(res, '用户名或密码错误');
    }

    // 检查账号状态
    if (!admin.status) {
      return response.error(res, '账号已被禁用');
    }

    // 生成token
    const token = generateToken(admin);

    // 返回用户信息和token
    return response.success(res, {
      token,
      user: {
        id: admin.id,
        username: admin.username,
        email: admin.email,
        nickname: admin.nickname,
        role: admin.role
      }
    }, '登录成功');
  } catch (error) {
    console.error('登录失败:', error);
    return response.error(res, '登录失败，请稍后重试');
  }
});

// 获取当前用户信息
router.get('/me', authenticateToken, async (req: AuthenticatedRequest, res: Response) => {
  try {
    const admin = await prisma.admin.findUnique({
      where: { id: req.user!.id },
      select: {
        id: true,
        username: true,
        email: true,
        nickname: true,
        role: true,
        status: true,
        createdAt: true
      }
    });

    if (!admin) {
      return response.error(res, '用户不存在', 404);
    }

    return response.success(res, admin, '获取用户信息成功');
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return response.error(res, '获取用户信息失败');
  }
});

// 修改密码
router.put('/change-password', authenticateToken, async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { oldPassword, newPassword } = req.body;

    if (!oldPassword || !newPassword) {
      return response.error(res, '请输入旧密码和新密码');
    }

    if (newPassword.length < 6) {
      return response.error(res, '新密码长度至少6位');
    }

    // 获取当前用户
    const admin = await prisma.admin.findUnique({
      where: { id: req.user!.id }
    });

    if (!admin) {
      return response.error(res, '用户不存在', 404);
    }

    // 验证旧密码
    const isValidPassword = await bcrypt.compare(oldPassword, admin.password);
    if (!isValidPassword) {
      return response.error(res, '旧密码错误');
    }

    // 加密新密码
    const hashedPassword = await bcrypt.hash(newPassword, 10);

    // 更新密码
    await prisma.admin.update({
      where: { id: req.user!.id },
      data: { password: hashedPassword }
    });

    return response.success(res, null, '密码修改成功');
  } catch (error) {
    console.error('修改密码失败:', error);
    return response.error(res, '修改密码失败');
  }
});

// 更新个人信息
router.put('/profile', authenticateToken, async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { email, nickname } = req.body;

    const admin = await prisma.admin.update({
      where: { id: req.user!.id },
      data: {
        email,
        nickname
      },
      select: {
        id: true,
        username: true,
        email: true,
        nickname: true,
        role: true
      }
    });

    return response.success(res, admin, '更新个人信息成功');
  } catch (error) {
    console.error('更新个人信息失败:', error);
    return response.error(res, '更新个人信息失败');
  }
});

// 创建初始管理员（仅在没有管理员时可用）
router.post('/init', async (req: Request, res: Response) => {
  try {
    // 检查是否已有管理员
    const adminCount = await prisma.admin.count();
    if (adminCount > 0) {
      return response.error(res, '管理员已存在');
    }

    const { username, password } = req.body;

    if (!username || !password) {
      return response.error(res, '请输入用户名和密码');
    }

    if (password.length < 6) {
      return response.error(res, '密码长度至少6位');
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建管理员
    const admin = await prisma.admin.create({
      data: {
        username,
        password: hashedPassword,
        role: 'admin',
        status: true
      }
    });

    return response.success(res, {
      id: admin.id,
      username: admin.username
    }, '初始管理员创建成功');
  } catch (error) {
    console.error('创建初始管理员失败:', error);
    return response.error(res, '创建初始管理员失败');
  }
});

export default router;